<template>
  <div class="breadcrumb_box">
    <el-tooltip class="item" :disabled="disabled" effect="dark" :content="title" placement="top">
      <el-breadcrumb class="app-breadcrumb" separator="/">
        <transition-group name="breadcrumb">
          <el-breadcrumb-item v-for="(item, index) in levelList" :key="item.path">
            <span v-if="item.redirect === 'noRedirect' || index == levelList.length - 1" class="no-redirect">{{
              item.meta.title
            }}</span>
            <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
          </el-breadcrumb-item>
        </transition-group>
      </el-breadcrumb>
    </el-tooltip>
    <i v-if="!disabled">…</i>
  </div>
</template>

<script>
export default {
  data() {
    return {
      levelList: null,
      title:'',
      disabled: false
    }
  },
  watch: {
    $route(route) {
      // if you go to the redirect page, do not update the breadcrumbs
      if (route.path.startsWith('/redirect/')) {
        return
      }
      this.title='';
      this.disabled = false;
      this.getBreadcrumb()
    }
  },
  created() {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb() {
      // only show routes with meta.title
      let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
      if (this.$route.matched && this.$route.matched.length > 2) this.$route.matched.splice(1, this.$route.matched.length - 2)
      const first = matched[0]

    //   if (!this.isDashboard(first)) {
    //     matched = [{ path: '/index', meta: { title: '首页' }}].concat(matched)
    //   }
      if (matched.length < 4) {
        this.levelList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false);
        this.title = '';
        this.disabled = true;
      } else {
        var copList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false);
        this.levelList = matched.slice(0, 3).filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false);
        for (var i = 0; i < copList.length; i++) {
          this.title +=  copList[i].meta.title +' / ' ;
        }
        this.title = this.title.slice(0,this.title.length-2)
        this.disabled = false;
      }
    },
    isDashboard(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim() === '首页'
    },
    handleLink(item) {
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(path)
    }
  }
}
</script>

<style lang="scss" scoped>
.breadcrumb_box{
  display: inline-block;
}
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 12px;
  position: relative;
  top: 2px;
//   line-height: 50px;
//   margin-left: 8px;

  .no-redirect {
    // color: #97a8be;
    cursor: text;
  }
}
</style>
